package com.sto.stoapp.activity.aviation;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.StoSelectTableActivity;
import com.sto.stoapp.broadcast.HomeBroadAction;
import com.sto.stoapp.dataprocess.ProcessScanCode;
import com.sto.stoapp.dataprocess.parcelable.GetTableParcel;
import com.sto.stoapp.dataprocess.parcelable.SelectTableParcel;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.SqlSelectTableManager;
import com.sto.stoapp.entity.AviationToPieceLogEntity;
import com.sto.stoapp.entity.DataBusinessEntity;
import com.sto.stoapp.listener.StoOnClickListener;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.manager.BlueWeigthManager;
import com.sto.stoapp.status.EnumScanCode;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BlueReadThread;
import com.sto.stoapp.util.BillFilterUtil;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseDialog;
import com.sto.stoapp.widget.StoHhmEditText;
import com.sto.stoapp.widget.StoHhmEditText.EditClickListener;
import com.sto.stoapp.widget.StoHhmRadioButton;
import com.sto.stoapp.widget.StoHhmRadioButton.KeyUpListener;
import com.sto.stoapp.widget.StoListenerActivity;

import java.util.ArrayList;
import java.util.List;

@SuppressLint("HandlerLeak")
public class StoAviationToPieceActivity extends StoListenerActivity {

	// 网点编号长度
	// private static final int SITE_LENGTH = 6;
	private final int COURIER_RESULT = 0xfe;
	private StoHhmEditText prevStation;
	private TextView weight;
	private StoHhmRadioButton goods, notgoods;
	private int itemType = 1;

	private String prevStationCode = "", prevStationName = "";
	private DataBusinessEntity dataBusiness;

	private List<EditText> edit = new ArrayList<EditText>();

	private boolean IS_24HOURS = false;

	private boolean FLAG_STATUS = false;
	private float blueWeight = -1;

	private String billNo="";

	private BaseDialog filterDialog=null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sto_avition_to_piece);
		this.setTitleBottom(R.string.to_piece,
				HomeBroadAction.AVIATION_SCANNER_BROAD);
		IS_24HOURS = this.getIntent().getBooleanExtra(
				UnifiedStaticType.IS_24HOURS, false);
		initPointLayout(true);
		initWidget();
		initListen();
		initScanListener();
		initScanRecordAdapter(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
		dataBusiness = new DataBusinessEntity();
		dataBusiness.initInsertData();
		bluetoothConnect();
	}

	private void initWidget() {
		weight = (TextView) this.findViewById(R.id.enter_count);
		goods = (StoHhmRadioButton) this.findViewById(R.id.goods);
		notgoods = (StoHhmRadioButton) this.findViewById(R.id.notgoods);
		code = (StoHhmEditText) this.findViewById(R.id.avi_odd_numbers_text);
		prevStation = (StoHhmEditText) this.findViewById(R.id.avi_prev_station);
		goods.setChecked(true);
		edit.add(code);
		edit.add(prevStation);
		addUploadTable(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
	}

	/**
	 * 监听控件
	 */
	private void initListen() {
		goods.setKeyUpBack(new KeyUpListener() {

			@Override
			public void onKeyUpBack() {
				onBackPressed();
			}
		});

		notgoods.setKeyUpBack(new KeyUpListener() {

			@Override
			public void onKeyUpBack() {
				onBackPressed();
			}
		});

		goods.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {
				itemType = 1;
				notgoods.setChecked(false);
			}
		});

		notgoods.setOnClickListener(new StoOnClickListener(this) {

			@Override
			public void mHonClick(View v) {
				itemType = 2;
				goods.setChecked(false);
			}
		});

		// 上一站
		prevStation.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				goods.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
//				selectPrevStation();
			}
		});

		findViewById(R.id.btn_select).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				selectPrevStation();
			}
		});

		// 单号
		code.setEditDelete(new EditClickListener() {

			@Override
			public void onEditDelete() {
				prevStation.requestFocus();
			}

			@Override
			public void onEditClickListener(View v) {
				codeProcess();
			}
		});

		for (EditText editListener : edit) {

			/*
			 * 监听EditText内容个数
			 */
			editListener.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {
					// 控件没有内容就清空编号
					if (prevStation.getText().toString().length() <= 0) {
						prevStationCode = "";
						prevStationName = "";
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		}
		setBluetoothCloseOpenListener(new BluetoothCloseOpenListener() {

			@Override
			public void listener() {
				closeBluetooth();
				new CloseThread().start();

			}
		});
	}

	private void codeProcess() {
		String codeName = code.getText().toString();

		GetTableParcel data;
		if (codeName.length() == 0) {
			Helper.showSoundToast(this, getString(R.string.code_empty), false);
		} else {
			if (codeName.length() == NEXT_STATION_LENGTH) {
				data = queryPrevStation(codeName);
				if (data != null) {
					prevStation.setText(data.getSelectName());
					prevStationCode = data.getSelectCode();
					prevStationName = data.getSelectName();
				} else {
					prevStationName = "";
					Helper.showSoundToast(this, getString(R.string.undefined),
							false);
				}
				code.setText("");
			} else {

				onScanResults(codeName);
				/*
				 * if (CheckScanCode(code.getText().toString())) {
				 * onScanResults(code.getText().toString()); } else {
				 * code.setText(""); }
				 */
			}
		}
	}

	@Override
	public void onBackPressed() {
		showNotice();
	}

	private void selectPrevStation() {
		try {
			SelectTableParcel tableParcel = new SelectTableParcel();
			if (prevStation.getText().toString().length() == 0) {
				tableParcel.setSelectSql(SqlSelectTableManager.SQL_NETSITE_ALL);
				tableParcel.setSelectField(new String[] {});
			} else {
				tableParcel
						.setSelectSql(SqlSelectTableManager.SQL_NETSITE_ONLY_LIKE);
				tableParcel.setSelectField(new String[] {
						"%" + prevStation.getText().toString() + "%",
						"%" + prevStation.getText().toString() + "%" });
			}
			tableParcel.setSelectCode(SITE_CODE_NUMBER);
			tableParcel.setSelectName(SITE_CODE_NAME);
			tableParcel.setProperty(null);
			Intent intent = new Intent(this, StoSelectTableActivity.class);
			intent.putExtra("tableData", tableParcel);

			startActivityForResult(intent, COURIER_RESULT);
		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("selectPrevStation", e.getMessage());
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == COURIER_RESULT && resultCode == RESULT_OK) {
			GetTableParcel courierEntity = data.getParcelableExtra("Name");
			if (courierEntity != null) {
				prevStation.setText(courierEntity.getSelectName());
				prevStation.setSelection(prevStation.length());
				prevStationCode = courierEntity.getSelectCode();

				if (prevStationCode.length() > 0) {
					prevStationName = courierEntity.getSelectName();
					code.requestFocus();
				}
			}
		} else if (requestCode == COURIER_RESULT
				&& resultCode == RESULT_FIRST_USER) {
			prevStation.setText("");
			prevStationCode = "";
			Helper.showSoundToast(StoAviationToPieceActivity.this,
					"未检索到数据,请到业务设置中更新数据", false);
		}
	}

	private boolean CheckScanCode(String code) {
		boolean ret = false;
		EnumScanCode status = ProcessScanCode.getInstance(this)
				.ScanCodeResolve(code,
						EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
		AviationToPieceLogEntity localAviationToPieceLogEntity = getLogEntity();
		localAviationToPieceLogEntity.code = code;
		switch (status) {
		// 条码空
		case CODE_EMPTY:
			// Helper.showSoundToast(this, getString(R.string.code_empty),
			// false);
			break;

		// 非法条码
		case CODE_ILLEGAL:
			localAviationToPieceLogEntity.cause = "非法条码";
			localAviationToPieceLogEntity.writeLog();
			Helper.showSoundToast(this, getString(R.string.error_code), false);
			break;
		// 成功条码
		case CODE_WAY_BILL:

			ret = true;
			break;
		default:
			break;
		}

		return ret;
	}

	private AviationToPieceLogEntity getLogEntity() {
		AviationToPieceLogEntity localAviationToPieceLogEntity = new AviationToPieceLogEntity();
		localAviationToPieceLogEntity.site_code = StoFilePreference
				.getInstance(this).getSiteCode();
		localAviationToPieceLogEntity.emp_code = StoFilePreference.getInstance(
				this).getUserCode();
		localAviationToPieceLogEntity.code = this.code.getText().toString();
		return localAviationToPieceLogEntity;
	}

	@SuppressLint("NewApi")
	private void processScanData() {
		AviationToPieceLogEntity localAviationToPieceLogEntity = getLogEntity();
		String str = this.weight.getText().toString();
		try {
			if (!str.isEmpty() && blueWeight <= 0) {
				Helper.showSoundToast(this, getString(R.string.no_weight_data),
						false);
				localAviationToPieceLogEntity.cause = ("重量异常," + str + ":" + this.blueWeight);
				localAviationToPieceLogEntity.writeLog();
				return;
			}
			if (!prevStationName.equals(prevStation.getText().toString())) {
				Helper.showSoundToast(this, "请选择正确的上一站", false);
				localAviationToPieceLogEntity.cause = "请选择正确的上一站";
				localAviationToPieceLogEntity.writeLog();
				return;
			}
			/*
			 * 将上一站设置为可选
			 * 
			 * @date 2014-50-28
			 */
			if (/*
				 * !prevStationCode.isEmpty() &&
				 */!code.getText().toString().isEmpty()) {

				billNo=code.getText().toString();

				float maxWeight=StoFilePreference.getInstance(this).getBlueWeight();

				if(blueWeight>maxWeight){
					ScanOff();
					filterDialog=new BaseDialog(this);
					filterDialog.setTitles("重量限制为【" + maxWeight + "】\n当前重量为【" + blueWeight + "】\n请确认重量是否准确");
					filterDialog.show();
					filterDialog.getvCanncel().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							ScanOpen();
						}
					});
					filterDialog.getvAccept().setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							filterDialog.dismiss();
							//Add by wj过滤单号
							boolean isFilter= BillFilterUtil.isFilter(billNo,StoAviationToPieceActivity.this);
							if(isFilter){
								showFilterDialog(billNo);
								return;
							}
							//End by wj
							if (addPieceRecord(billNo)) {
								addCodeNumber();
								setSaveData(true);
								// SoundManager.getInstance(this).playSuccessSound();
								Helper.showSoundAndVibrator(StoAviationToPieceActivity.this, true);
								addScanRecordInfo(billNo, weight
										.getText().toString());
							}
							// 提示插入数据失败
							else {
								Helper.showSoundToast(StoAviationToPieceActivity.this,
										getString(R.string.code_repeat), false);
							}
							code.setText("");
							ScanOpen();
						}
					});
				}else {
					//Add by wj过滤单号
					boolean isFilter= BillFilterUtil.isFilter(billNo,this);
					if(isFilter){
						showFilterDialog(billNo);
						return;
					}
					//End by wj
					if (addPieceRecord(billNo)) {
						this.addCodeNumber();
						setSaveData(true);
						// SoundManager.getInstance(this).playSuccessSound();
						Helper.showSoundAndVibrator(this, true);
						addScanRecordInfo(code.getText().toString(), weight
								.getText().toString());
					}
					// 提示插入数据失败
					else {
						Helper.showSoundToast(this,
								getString(R.string.code_repeat), false);
					}
					code.setText("");
					ScanOpen();
				}
			} else if (!code.getText().toString().isEmpty()) {
				/*
				 * // 提示上一站不能为空 if (prevStationCode.isEmpty()) {
				 * Helper.showSoundToast(this, "上一站不能为空", false);
				 * prevStation.requestFocus(); }
				 */
			}

		} catch (Exception e) {
			e.printStackTrace();
			ExceptionLog.writeLog("processScanData", e.getMessage());
		}
	}

	private boolean addPieceRecord(String billNo) {
		boolean ret;

		// 扫描类型
		dataBusiness
				.setCommand_type(EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE
						.getOpCode());
		// 单号
		dataBusiness.setBar_code_number(billNo);
		dataBusiness.setCodeType(getExpType(billNo));
		// 物品类别
		dataBusiness.setFunction_type(String.valueOf(itemType));
		// 网点编号
		dataBusiness.setNet_code(StoFilePreference.getInstance(this)
				.getSiteCode());
		// 工号
		dataBusiness.setJob_number(StoFilePreference.getInstance(this)
				.getUserCode());
		// 上一站
		dataBusiness.setNext_station(prevStationCode);
		// 上一站名称
		dataBusiness.setUser_defined3(prevStation.getText().toString());
		// 蓝牙重量
		if (blueWeight > 0) {
			// 重量
			dataBusiness.setWeight(String.valueOf(blueWeight));
			blueWeight = -1;
		}
		if (IS_24HOURS == true) {
			dataBusiness.setDifferent_flag("1");
		}
		// 插入数据
		ret = StoDataBaseOperation.getInstance(this).insert(dataBusiness,
				EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
//		if (!ret && !("").equals(dataBusiness.getWeight())) {
//			ret = StoDataBaseOperation.getInstance(this).replace(dataBusiness,
//					EnumTableNames.STATUS_TABLE_AVIATION_SCAN_TO_PIECE);
//			if (ret) {
//				removeItem(code.getText().toString(), 1);
//			}
//		}
		return ret;
	}

	private void bluetoothConnect() {
		mBTAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBTAdapter != null) {
			if (mBTAdapter.isEnabled()) {
				weight.setText(R.string.now_connect_blue);
				blueConnecting();
			} else {
				// weight.setText(R.string.blue_no_open);
			}
		} else {
			// promptDialog(getText(R.string.blue_not_available).toString());
		}
	}

	private void blueConnecting() {
		String macAddress = StoFilePreference.getInstance(this)
				.getBluetoothMacAddress();
		if (!macAddress.equals("")) {
			if (blueConnectThread != null) {
				blueConnectThread.cancelDialog();
				blueConnectThread.clearBlueDevices();
				blueConnectThread = null;
			}
			// weight.setEnabled(false);
			blueConnectThread = new BlueReadThread(this, bluetoothHandler,
					macAddress, false);
			blueConnectThread.start();
		} else {
			weight.setText(R.string.select_blue_scales);
		}
	}

	private Handler bluetoothHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Log.d("logdebug:", "msg.what:" + msg.what);
			if (msg.what == BlueWeigthManager.UPDATE_BLUE_DATA) {
				if (blueConnectThread != null) {
					blueConnectThread.cancelDialog();
				}
				if (msg.obj != null && !msg.obj.toString().equals("")) {
					String result = msg.obj.toString();
					Log.d("msg=", String.valueOf(result));
					// 表示连接蓝牙失败
					if (result.equals(BlueWeigthManager.CONNECT_FAIL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							if (blueConnCount < 3) {
								blueConnecting();
								blueConnCount++;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",正在重连" + blueConnCount + "...");
							} else {
								blueConnCount = 0;
								weight.setText(getText(
										R.string.blue_connect_fail).toString()
										+ ",请到系统设置, 重新设置蓝牙!");
							}
						}
					}
					// 没有选择秤型号
					else if (result
							.equals(BlueWeigthManager.NO_SELECT_SCALE_MODEL)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(getText(
									R.string.no_select_scales_model).toString()
									+ "请到系统设置,设置蓝牙!");

						}

					}
					// 读取数据失败
					else if (result.equals(BlueWeigthManager.READ_ERROR)) {
						blueWeight = -1;
						if (blueConnectThread != null) {
							weight.setText(R.string.get_data_error);
						}
					} else {
						// 显示重量
						blueWeight = parseFloat(result);
						weight.setText(result);
					}
				}
			}
		}

	};

	@Override
	protected void onDestroy() {
		// 取消蓝牙连接
		edit.clear();
		edit = null;
		// closeBluetooth();

		bluetoothHandler.removeMessages(BlueWeigthManager.UPDATE_BLUE_DATA);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	// @Override
	// protected void doBack() {
	// if (BluetoothAdapter.getDefaultAdapter().isEnabled()
	// && blueConnectThread != null && !blueConnectThread.isConnected()) {
	// handler.sendEmptyMessageAtTime(5, 5000);
	// showDialog();
	// } else {
	// super.doBack();
	// }
	// }
	/*
	 * // 设置蓝牙 private void selectBlueDevice(String str) { if (FLAG_STATUS) {
	 * return; } FLAG_STATUS = true; BaseDialog dialog = new BaseDialog(this);
	 * dialog.setTitles(str + " " + getString(R.string.yesorno_set_blue));
	 * dialog.show(); dialog.setOnBackClickListener(new OnBackClickListener() {
	 * 
	 * @Override public void onBackClickListener(boolean res) { if (res) { //
	 * 取消蓝牙连接 if (mBTAdapter != null) { if (mBTAdapter.isEnabled()) { if
	 * (bluemanager != null) { bluemanager.cancelConnect(); bluemanager = null;
	 * } } } Intent intent = new Intent(StoAviationToPieceActivity.this,
	 * SystemBlueWeigthSettingActivity.class); intent.putExtra("busiType",
	 * HomeBroadAction.SCANNER_MAN_BROAD); startActivity(intent); } FLAG_STATUS
	 * = false; } }); }
	 */

	@Override
	protected void handlerScanData(String scanData) {

		if(null!=filterDialog && filterDialog.isShowing()){
			return;
		}

		if (scanData != null && !scanData.equals("")) {
			String result = scanData;
			// 上一站编号
			if (result.length() == NEXT_STATION_LENGTH) {
				prevStation.setText(result);
				selectPrevStation();
			} else {
				code.setText(result);
				code.setSelection(code.length());

				if (CheckScanCode(result)) {
					processScanData();
				}
				code.setText("");
			}
		} else {
		}

	}

}